package com.example.docsearcher.controller;

import com.example.docsearcher.search.DocResult;
import com.example.docsearcher.search.DocSearch;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import java.util.List;

@RestController
public class DocSearcherController {
    private static DocSearch docSearch;

    static {
        try {
            docSearch = new DocSearch();
        } catch (InterruptedException e) {
            throw new RuntimeException(e);
        }
    }

    private ObjectMapper objectMapper = new ObjectMapper();

    @RequestMapping("/searcher")
    public String search(@RequestParam("query") String query) throws JsonProcessingException {
        System.out.println("query: " + query);
        // 参数是查询词，返回值是相应内容
        // 参数 query 来自 url 中的query string 中的query 这个 key 的值
        List<DocResult> results = docSearch.search(query);
        String json = objectMapper.writeValueAsString(results);
        return objectMapper.writeValueAsString(results);
    }
}
